package mail.db;

import java.sql.SQLException;

import javax.mail.Folder;
import javax.mail.MessagingException;
import javax.mail.Store;

import mail.BadProtocolException;
import mail.IMAPConnection;
import mail.UserInfo;
import mail.folder.MailFolder;
import mail.owner.Owner;

public class MailArchiver {
	
	
	private DataBase db;
	private IMAPConnection imapConn;
	private Owner owner;
	
	public MailArchiver(DataBase db, IMAPConnection imapConn) throws SQLException {
		this.db = db;
		this.imapConn = imapConn;
		this.owner = new Owner(imapConn.getAuthenticator().getName(), imapConn.getAuthenticator().getEmail());
	}
	
	public void insertMessages() throws MessagingException {
		Store store = imapConn.getStore();
		Folder root = store.getDefaultFolder();
	}
	
	public void createFolders() throws MessagingException, SQLException {
		imapConn.connect();
		Store store = imapConn.getStore();
		Folder root = store.getDefaultFolder();
		
		recCreateFolders(root, null);
		imapConn.disconnect();
		System.out.println("Total queries = "+db.getQueryCount());
	}
	
	private void recCreateFolders(Folder cur, MailFolder parent) throws MessagingException, SQLException {
		MailFolder root;
		
		if (cur.getName().length() < 1)
			root = new MailFolder(owner, "ROOT", parent);
		else
			root = new MailFolder(owner, cur, parent);
		
		for (Folder next : cur.list()) {
			recCreateFolders(next, root);
		}
	}
	
	public static void main(String[] args) throws SQLException, BadProtocolException, MessagingException {
		MailArchiver ma = new MailArchiver(DataBase.getInstance(), new IMAPConnection(UserInfo.name, UserInfo.email, UserInfo.password, false));
		ma.createFolders();
	}
}
